import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import createPersistedState from "vuex-persistedstate"
export default new Vuex.Store({
  //数据持久化
  plugins: [createPersistedState({
      storage: window.sessionStorage,
      reducer(val) {
          return {
          // 只储存state中的assessmentData
          cartData: val.cartData
        }
      }
  })],
  // 数据源
  state: {
    //购物车列表
    cartData:[],
    // cartData:localStorage["cartData"]?JSON.parse(localStorage["cartData"]): [],
    cartTotalPrice:0,
    // cart:''
    token:'',
    users:''
  },
  getters: {
    cartTotalPrice(state){
      return state.cartData.reduce((prev,next)=>{
        return prev + next.officialPrice * next.num
      },0)
    },
  },
  mutations: {
    //加入购物车
    setitem(state,data){
          let datas={       //传入的商品属性
              img:data.img,
              num:1,
              name:data.name,
              supplierTitle:data.supplierTitle,
              officialPrice:data.officialPrice,
              goodsid:data.goodsid
          }
          let index = state.cartData.findIndex(item=>{
                return item.goodsid == data.goodsid
          })
          if(index==-1){    //返回-1说明购物车里没有这个商品，则push进去，如果返回下标，则让此商品的数量加1
              // localStorage.setItem('cartData', JSON.stringify(datas));
              state.cartData.push(datas)
           }else{
              state.cartData[index].num++
           }
    },
    //减
    incr(state,index){
        state.cartData[index].num --
    },
    //加
    decr(state,index){
      state.cartData[index].num ++
    },
    // 删除
    dele(state,goodsid){
      let index = state.cartData.findIndex(item=>{
          return item.goodsid == goodsid
      })
      // console.log(index);
      state.cartData.splice(index,1)
    },
    cart(state,data){
      state.cart = data
    },
    settoken(state, token) {
      state.token = token
    },
    setusers(state,users){
     state.users=users
    }
  },
  actions: {
    //加入购物车
    items({commit},data){
      commit('setitem',data)
      // console.log(data);
    },
    //减
    incr({commit},index){
      commit('incr',index)
      // console.log(index);
    },
    //加
    decr({commit},index){
      commit('decr',index)
      // console.log(index);
    },
    //删除
    dele({commit},goodsid){
      commit('dele',goodsid)
    },
    //本地存储
    cart({commit},data){
      commit('cart',data)
      sessionStorage.setItem('cart',data)
    },
    token({ commit }, token) {
      // 存token在session
      commit('settoken', token)
      sessionStorage.setItem('token', token)
    },
    users({commit},users){
      commit('setusers', users)
    }
  },
  //   store.subscribe(()=>{
  //     localStorage.setItem('cart', JSON.stringify(store.state.cart));
  //     console.log('以保存')
  // })
})